﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;

/// <summary>
/// Summary description for HttpUtility
/// </summary>
public class HttpUtility
{
	public HttpUtility()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    /// <summary>
    /// 
    /// </summary>
    /// <param name="address"></param>
    /// <param name="responseSource"></param>
    /// <returns></returns>
    /// <exception cref="">Throws exception if error occurs</exception>
    public static bool GetResponseSource(string address, out string responseSource)
    {
        responseSource = string.Empty;
        HttpWebResponse response = null;
        if (string.IsNullOrEmpty(address)) { throw new ArgumentNullException("HTTP address"); }
        try
        {
            Uri uri = new Uri(address);
            // Create and initialize the web request  
            HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
            request.UserAgent = "ASP.NET Car Offers Client";
            request.KeepAlive = false;
            // Set timeout to 15 seconds  
            request.Timeout = 15 * 1000;
            // Get response  
            response = request.GetResponse() as HttpWebResponse;
            if (request.HaveResponse == true && response != null)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());
                // Read it into a StringBuilder  
                StringBuilder sbSource = new StringBuilder(reader.ReadToEnd());
                responseSource = sbSource.ToString();
                // Console application output  
                Console.WriteLine(responseSource);
                return true;
            }
            responseSource = "Response not received";
            return false;
        }
        catch (WebException wex)
        {
            // This exception will be raised if the server didn't return 200 - OK  
            // Try to retrieve more information about the network error  
            if (wex.Response != null)
            {
                using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                {
                    string errorMsg = string.Format("The server returned '{0}' with the status code {1} ({2:d}).",
                        errorResponse.StatusDescription, errorResponse.StatusCode,
                        errorResponse.StatusCode);
                    Console.WriteLine(errorMsg);
                    responseSource = errorMsg;
                    return false;
                }
            }
            throw;
        }
        finally
        {
            if (response != null) { response.Close(); }
        }
    }  
}